﻿using HouseResourceAnalysis.Target;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HouseResource.Forms
{
    public partial class TermsManager : Form
    {
        public TermsManager()
        {
            InitializeComponent();
        }

        private void AppendText(List<string> terms)
        {
            string content = string.Join(Environment.NewLine, terms);
            string oldText = System.IO.File.ReadAllText(BaseResource.TermsFile);

            FileStream fs = new FileStream(BaseResource.TermsFile, FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(fs);
            //开始写入
            sw.Write(content + Environment.NewLine + oldText);
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
        }

        private void btnStudy_Click(object sender, EventArgs e)
        {
            List<string> results = new List<string>();
            string url = "http://cs.fang.anjuke.com/loupan/all/";
            SetLog($"分词训练目标网址：{url}");
            new Task(() =>
            {
                AnJuKe house = new AnJuKe() { Url = url };
                var detailLinks = house.GetDetailLinks();
                SetLog($"获取楼盘数:{detailLinks.Count}");
                foreach (var item in detailLinks)
                {
                    var model = house.GetHouse(item);
                    var terms = ReplaceOhter(model.Name);
                    SetLog($"获取楼盘名称：{model.Name}，捕获分词：【{terms}】");
                    results.Add(terms);
                }
                AppendText(results);
                SetLog($"本次分词学习总数：{results.Count}");
                MessageBox.Show($"本次分词学习总数：{results.Count},已同步更新分词库。");
            }).Start();
        }

        private string ReplaceOhter(string str)
        {
            foreach (var item in BaseResource.FilterKeywords)
            {
                str = str.Replace(item, string.Empty);
            }
            return str;
        }

        private void SetLog(string msg)
        {
            txtTerms.BeginInvoke((MethodInvoker)delegate ()
            {
                txtTerms.Text = $"{msg}{Environment.NewLine}" + txtTerms.Text;
            });
        }
    }
}